package cn.mineserv.video.videoordersystem.controller;


import cn.mineserv.video.videoordersystem.model.Media;
import cn.mineserv.video.videoordersystem.model.User;
import cn.mineserv.video.videoordersystem.service.MediaService;
import cn.mineserv.video.videoordersystem.utils.Util;
import com.alibaba.fastjson2.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;


@Controller
@RequestMapping("/common")
public class CommonController {
    @Value("${path.upload}")
    private String uploadPath;

    @Resource
    private MediaService mediaService;

    @Value("${server.servlet.context-path}")
    private String contextPath;
    @PostMapping(path = "/uploadMd")
    public String uploadMd(MultipartFile[] file, Media media, HttpServletRequest request) {
        //处理文件
        User user = (User) request.getSession().getAttribute("user");
        media.setUserId(user.getUserId());
        int i=3;
        JSONObject jsonObject = new JSONObject();
        for (MultipartFile file1 : file){
            String fileName = file1.getOriginalFilename();

            assert fileName != null;
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            if (StringUtils.isBlank(suffix)) {
                jsonObject.put("url", "实在抱歉，有错误了！");
                jsonObject.put("success", 0);
                jsonObject.put("message", "upload success!");
            }
            // 生成随机文件名
            fileName = Util.generateUUID() + suffix;
            // 确定文件存放的路径
            File dest = new File(uploadPath + "/" + fileName);
            try {
                // 存储文件
                file1.transferTo(dest);
            } catch (IOException e) {

                jsonObject.put("url", "实在抱歉，有错误了！");
                jsonObject.put("success", 0);
                jsonObject.put("message", "upload success!");
                throw new RuntimeException("上传文件失败,服务器发生异常!", e);
            }

            String headerUrl = "http://localhost:8080" + contextPath + "/common/image/" + fileName;
            if (i==3){
                media.setMediaCover(headerUrl);
                i=2;
            }else{
                media.setMediaDownload(headerUrl);
            }

            jsonObject.put("url", headerUrl);
            jsonObject.put("success", 1);
            jsonObject.put("message", "upload success!");
        }
        media.setMediaUploadTime(new Date());
        media.setMediaStatus(0);
        media.setMediaLike(0);

            mediaService.save(media);
        return "/media/video/UpdateVideo";
    }
    /**
     * 获取文件
     * @param fileName
     * @param response
     */
    @GetMapping(path = "/image/{fileName}")
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        // 服务器存放路径
        fileName = uploadPath + "/" + fileName;
        // 文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 响应图片
//        response.setContentType("image/" + suffix);
        try (
                FileInputStream fis = new FileInputStream(fileName);
                OutputStream os = response.getOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            System.out.println("失败");
        }
    }
}
